﻿using AutoMapper;
using B.S.RbacData.Domain.Traceabilitys;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Write.API.Applications.Commands.Traceabilitys;
using MediatR;
using System.Security.Claims;

namespace B.S.RbacData.Write.API.Applications.Commandhandlters.Traceabilitys
{
    /// <summary>
    /// 更新产品信息命令处理器
    /// </summary>
    public class UpdateProductCommandHandlter : IRequestHandler<UpdateProductCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ProductModel> productRep;
        private readonly IMapper mapper;
        private readonly IHttpContextAccessor httpContextAccessor;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="productRep">产品信息仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="httpContextAccessor">HTTP上下文访问器</param>
        public UpdateProductCommandHandlter(
            IBaseRepository<ProductModel> productRep
           , IMapper mapper, IHttpContextAccessor httpContextAccessor)
        {
            this.productRep = productRep;
            this.mapper = mapper;
            this.httpContextAccessor = httpContextAccessor;
        }
        
        /// <summary>
        /// 处理更新产品信息请求
        /// </summary>
        /// <param name="request">更新产品信息请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>返回操作结果</returns>
        public async Task<ApiResult<int>> Handle(UpdateProductCommand request, CancellationToken cancellationToken)
        {
            // 获取当前登录用户ID
            var userId = Convert.ToInt32(httpContextAccessor.HttpContext.User.FindFirstValue("UserId"));

            // 查找当前要更新的产品信息
            var currentProduct = productRep.GetAll()
                .FirstOrDefault(p => p.ID == request.ID && !p.IsDeleted);
                
            if (currentProduct == null)
            {
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = "找不到要修改的产品信息"
                };
            }

            // 如果商品ID变更了，检查是否有其他产品关联到同一个商品
            if (currentProduct.GoodsId != request.GoodsId)
            {
                var duplicateProduct = productRep.GetAll()
                    .FirstOrDefault(p => p.GoodsId == request.GoodsId && p.ID != request.ID && !p.IsDeleted);

                if (duplicateProduct != null)
                {
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = "商品信息已存在，请确保商品信息唯一"
                    };
                }
            }

            // 更新当前实体的属性，而不是创建新的实体
            currentProduct.GoodsId = request.GoodsId;
            currentProduct.ProductionBatch = request.ProductionBatch;
            currentProduct.ShelfLifeDay = request.ShelfLifeDay;
            currentProduct.ProductionLicenseNumber = request.ProductionLicenseNumber;
            currentProduct.Manufacturer = request.Manufacturer;
            currentProduct.CoverImage = request.CoverImage;
            currentProduct.UpdateTime = DateTime.Now;
            currentProduct.UpdateUserId = userId;
           
            // 执行更新操作
            var result = await productRep.UpdateAsync(currentProduct);

            // 返回操作结果
            return new ApiResult<int>
            {
                code = result > 0 ? ResultEnumCode.Ok : ResultEnumCode.fails,
                data = result,
                message = result > 0 ? "修改产品信息成功" : "修改产品信息失败"
            };
        }
    }
}
